var is_pc = true;//是pc吗？
var history = [];
if (document.body.clientWidth < 600) is_pc = false;

if (window.innerHeight > window.innerWidth) document.body.background = "./res/bg_mobile.jpg";

layui.use(['dropdown', 'util', 'layer', 'jquery', 'laypage', 'laytpl'], function () {
  var element = layui.element;
  var layer = layui.layer;
  var $ = layui.jquery;
  var date = new Date();
  var laypage = layui.laypage;
  var laytpl = layui.laytpl;


  function render_task() {
    var day_array = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    $("#head_time").html(date.getFullYear() + "." + (date.getMonth() + 1) + "." + date.getDate() + "/" + day_array[date.getDay()]);

    var load = layer.load(0, { time: 10 * 1000 });
    $.ajax({
      url: './back_end/sql.php',
      type: 'post',
      data: { "option": "select" },
      async: false,
      success: function (res) {
        // //console.log(res);
        var temp = JSON.parse(res);
        // //console.log(JSON.parse(res));

        var data = { "class": temp.class, "task": {} }
        for (var i in temp["class"]) {
          data["task"][temp["class"][i].class_id] = [];
        }
        for (i in temp["task"]) {
          data["task"][temp["task"][i].task_class].push(temp["task"][i]);
        }
        //console.log(data);
        if (is_pc) {
          var getTpl = tasks.innerHTML
            , view = document.getElementById('task_view');
        }
        else {
          var getTpl = tasks_phone.innerHTML
            , view = document.getElementById('task_view');
        }

        laytpl(getTpl).render(data, function (html) {
          view.innerHTML = html;
        });
      }
      //…
    });
    layer.close(load);
  }

  function render_history() {

    var load = layer.load(0, { time: 10 * 1000 });
    $.ajax({
      url: './back_end/sql.php',
      type: 'post',
      data: { "option": "getCount", "tableName": "task" },
      async: false,
      success: function (res) {
        laypage.render({
          elem: 'pages' //注意，这里的 test1 是 ID，不用加 # 号
          , count: JSON.parse(res)["result"] //数据总数，从服务端得到
          , limit: (is_pc ? 20 : 4)
          , layout: ['prev', 'next']
          , prev: "Front"
          , next: "Next"
          , jump: function (obj, first) {
            //obj包含了当前分页的所有参数，比如：
            //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
            //console.log(obj.limit); //得到每页显示的条数

            // //首次不执行
            // if (!first) {
            //   //do something
            // }
            var up=(obj.curr-1)*obj.limit;

            var temp={"limit":"limit "+up+","+obj.limit}
            var load1 = layer.load(0, { time: 10 * 1000 });
            $.ajax({
              url: './back_end/sql.php',
              type: 'post',
              data: { "option": "history","data":temp},
              async: false,
              success: function (res) {
                var data = JSON.parse(res);
                //console.log(res);
                if (is_pc) {
                  var getTpl = history_items.innerHTML
                    , view = document.getElementById('history_view');
                }
                else {
                  var getTpl = history_items_phone.innerHTML
                    , view = document.getElementById('history_view');
                }
                laytpl(getTpl).render(data, function (html) {
                  view.innerHTML = html;
                });

                layer.close(load1);
              }
              //…
            });
          }
        });
        layer.close(load);
      }
      //…
    });





  }
  function render_class() {
    var load = layer.load(0, { time: 10 * 1000 });
    $.ajax({
      url: './back_end/sql.php',
      type: 'post',
      data: { "option": "class" },
      async: false,
      success: function (res) {
        var data = JSON.parse(res);
        //console.log(data);

        var getTpl = class_items.innerHTML
          , view = document.getElementById('class_view');
        laytpl(getTpl).render(data, function (html) {
          view.innerHTML = html;
        });
      }
      //…
    });
    layer.close(load);
  }
  render_task();
  //监听折叠
  element.on('tab(test1)', function () {
    // layer.msg("77777777778888888888888");
    switch (this.getAttribute('lay-id')) {
      case "1":
        render_task();
        break;
      case "2":
        render_history();
        break;
      case "3":
        render_class();
        break;
      default: break;
    }
  });




});


function addTask(class_name, class_id) {
  layui.use(['dropdown', 'util', 'layer', 'jquery', 'laypage', 'laytpl', 'laydate', 'form'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.jquery;
    var date = new Date();
    var laypage = layui.laypage;
    var laytpl = layui.laytpl;
    var laydate = layui.laydate;
    var form = layui.form;

    var html = addTaskForm.innerHTML;
    laytpl(html).render({ "class_name": class_name, "class_id": class_id }, function (res) {
      html = res;
    });
    var addLayer = layer.open({
      type: 1,
      title: 'New Task',
      offset: 'auto',
      area: '95%',
      content: html, //这里content是一个普通的String
      cancel: function (index, layero) {
        // window.location.reload();
      }
    });
    layer.style(addLayer, {
      opacity: 0.9,
    });
    laydate.render({
      elem: '#task_startTime' //指定元素
      , value: new Date()
    });
    laydate.render({
      elem: '#task_deadline' //指定元素
      , value: new Date()
    });
    form.on('submit(saveNewTask)', function (data) {
      var load = layer.load(0, { time: 10 * 1000 });
      //console.log(data.field);
      layer.close(load);
      $.ajax({
        url: './back_end/sql.php',
        type: 'post',
        data: { "option": "insert", "data": JSON.stringify(data.field), "tableName": "task" },
        async: false,
        success: function (res) {
          //console.log(res);
          var data = JSON.parse(res);
          //console.log(data);
          if (data.result == "0") {
            layer.msg("Success!")
            layer.close(addLayer);
            $("#tab1").click();
            return;
          }
          layer.msg("Add Failure！")
        }
        //…
      });
      return false;
    });

  })
}


function addClass() {
  layui.use(['dropdown', 'util', 'layer', 'jquery', 'laypage', 'laytpl', 'laydate', 'form'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.jquery;
    var date = new Date();
    var laypage = layui.laypage;
    var laytpl = layui.laytpl;
    var laydate = layui.laydate;
    var form = layui.form;

    var html = addClassForm.innerHTML;
    var addLayer = layer.open({
      type: 1,
      title: 'New Class',
      offset: 'auto',
      area: '95%',
      content: html, //这里content是一个普通的String
      cancel: function (index, layero) {
        // window.location.reload();
      }
    });
    layer.style(addLayer, {
      opacity: 0.9,
    });

    form.on('submit(saveNewClass)', function (data) {
      var load = layer.load(0, { time: 10 * 1000 });
      //console.log(data.field);
      layer.close(load);
      $.ajax({
        url: './back_end/sql.php',
        type: 'post',
        data: { "option": "insert", "data": JSON.stringify(data.field), "tableName": "class" },
        async: false,
        success: function (res) {
          //console.log(res);
          var data = JSON.parse(res);
          //console.log(data);
          if (data.result == "0") {
            layer.msg("Success!")
            layer.close(addLayer);
            $("#tab3").click();
            return;
          }
          layer.msg("Add Failure！")
        }
        //…
      });
      return false;
    });

  })
}

function delete_info(type, id) {
  layui.use(['dropdown', 'util', 'layer', 'jquery', 'laypage', 'laytpl', 'laydate', 'form'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.jquery;
    var date = new Date();
    var laypage = layui.laypage;
    var laytpl = layui.laytpl;
    var laydate = layui.laydate;
    var form = layui.form;
    var data = { "id_name": type + "_id", "id": id };
    layer.confirm('sure to delete?', { icon: 3, title: 'tips' }, function (index) {
      //do something
      //console.log(data);
      var load = layer.load(0, { time: 10 * 1000 });
      $.ajax({
        url: './back_end/sql.php',
        type: 'post',
        data: { "option": "delete", "data": JSON.stringify(data), "tableName": type },
        async: false,
        success: function (res) {
          //console.log(res);
          var data = JSON.parse(res);
          //console.log(data);
          if (data.result == "0") {
            layer.msg("Success!")
            // window.location.reload();
            layer.close(load);
            layer.close(index);
            $("#tab2").click();
            return;
          }
          layer.msg("Delete Failure！")
        }
      });
      layer.close(index);
    });


  })
}

function update_info(type, id, param_name, param_value) {
  layui.use(['dropdown', 'util', 'layer', 'jquery', 'laypage', 'laytpl', 'laydate', 'form'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.jquery;
    var date = new Date();
    var laypage = layui.laypage;
    var laytpl = layui.laytpl;
    var laydate = layui.laydate;
    var form = layui.form;
    var data = { "id_name": type + "_id", "id": id, "param_name": param_name, "param_value": param_value };
    layer.confirm('Are you sure?', { icon: 3, title: 'tips' }, function (index) {
      //do something
      //console.log(data);
      var load = layer.load(0, { time: 10 * 1000 });
      $.ajax({
        url: './back_end/sql.php',
        type: 'post',
        data: { "option": "update", "data": JSON.stringify(data), "tableName": type },
        async: false,
        success: function (res) {
          //console.log(res);
          var data = JSON.parse(res);
          //console.log(data);
          if (data.result == "0") {
            layer.msg("Success!")

            // window.location.reload();
            layer.close(load);
            layer.close(index);
            switch (type) {
              case "task":
                {
                  if (param_value == '0' || param_value == '-1') {
                    // layer.msg("tab2click");
                    $("#tab2").click();
                  }
                  else {
                    // layer.msg("tab1click");
                    $("#tab1").click();
                  }
                }
                break;
              case "class": $("#tab3").click(); break;
            }
            return;
          }
          layer.msg("Update Failure！")
        }
      });
      layer.close(index);
    });


  })
}


function top_this(type, id) {
  layui.use(['dropdown', 'util', 'layer', 'jquery', 'laypage', 'laytpl', 'laydate', 'form'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.jquery;
    var date = new Date();
    var laypage = layui.laypage;
    var laytpl = layui.laytpl;
    var laydate = layui.laydate;
    var form = layui.form;
    var data = { "id_name": type + "_id", "id": id };

    //do something
    //console.log(data);
    var load = layer.load(0, { time: 10 * 1000 });
    $.ajax({
      url: './back_end/sql.php',
      type: 'post',
      data: { "option": "top", "data": JSON.stringify(data), "tableName": type },
      async: false,
      success: function (res) {
        //console.log(res);
        var data = JSON.parse(res);
        //console.log(data);
        if (data.result == "0") {
          // layer.msg("Success!")

          // window.location.reload();
          layer.close(load);
          switch (type) {
            case "task":
              $("#tab1").click();
              break;
            case "class":
              $("#tab3").click();
              break;
          }
          return;
        }
        // layer.msg("Update Failure！")
      }
    });


  })
}


